package cn.itcast.cd.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import cn.itcast.cd.dao.IPermissionDao;
import cn.itcast.cd.domain.Permission;
import cn.itcast.cd.domain.Product;
import cn.itcast.cd.domain.PurchaseBill;
import cn.itcast.cd.domain.PurchaseBillItem;
import cn.itcast.cd.domain.Role;
import cn.itcast.cd.domain.Supplier;
import cn.itcast.cd.service.IPermissionService;
import cn.itcast.cd.service.IProductDirService;
import cn.itcast.cd.service.IPurchaseBillService;
import cn.itcast.cd.service.ISupplierService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PurchaseBillAction extends ActionSupport {

	private IPurchaseBillService purchaseBillService;

	public void setPurchaseBillService(IPurchaseBillService purchaseBillService) {
		this.purchaseBillService = purchaseBillService;
	}

	private ISupplierService supplierService;
	private PurchaseBill bill = new PurchaseBill();
	private List<PurchaseBillItem> billItems = new ArrayList<PurchaseBillItem>();

	public List<PurchaseBillItem> getBillItems() {
		return billItems;
	}

	private Product product = new Product();

	public Product getProduct() {
		return product;
	}

	private Supplier supplier = new Supplier();

	public PurchaseBill getBill() {
		return bill;
	}

	public void setSupplierService(ISupplierService supplierService) {
		this.supplierService = supplierService;
	}

	public String input() {

		// 准备供应商数据.
		List<Supplier> suppliers = supplierService.queryEntity(
				"SELECT s From Supplier s", null);
		// System.out.println(suppliers);
		ActionContext.getContext().put("suppliers", suppliers);
		return INPUT;
	}

	public String save() {
		bill.setItems(billItems);
		if(bill.getId()==null){
			purchaseBillService.save(bill);
		}else if(bill.getId()!=null){
			purchaseBillService.update(bill);
		}
		return SUCCESS;
	}

	public String delete() {
		if(bill.getId()!=null){
			purchaseBillService.delete(bill.getId());
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html;charset=utf-8");
			try {
				response.getWriter().println("{\"success\":\"删除数据成功\"}");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return NONE;
	}

	public String list() {
		String conditions = "FROM PurchaseBill";
		List<PurchaseBill> bills = purchaseBillService.queryEntity(conditions, null);
		ActionContext.getContext().put("bills", bills);
		return "list";
	}
	
	public String edit(){
		bill = purchaseBillService.get(bill.getId());
		return input();
	}

}
